class LazyLoad {
  constructor(selector) {
    this.imgsList = [...document.querySelectorAll(selector)];
    this.top_list = this.imgsList.map(item => $(item).offset().top);
    this.bindEvent();
    $(document).trigger('scroll');
  }
  bindEvent() {
    $(document).on('scroll', throttle(() => {
      this.lazyload();
    }, 100));
  }
  lazyload() {
    for (let i = 0; i < this.imgsList.length; i++) {
      if (this.top_list[i] <= $(document).scrollTop() + $(window).height()) {
        let image = new Image();
        $(image).prop('src', $(this.imgsList[i]).attr('data-src'));
        let img = this.imgsList[i];
        image.addEventListener('load', () => {
          $(img).prop('src', $(img).attr('data-src'));
        });
        // $(this.imgsList[i]).prop('src', $(this.imgsList[i]).attr('data-src'));
        this.imgsList.splice(i, 1);
        this.top_list.splice(i, 1);
        i--;
      }
    }
  }
}

class WaterFall {
  constructor(wrap, selector) {
    this.wrapper = document.querySelector(wrap);
    this.lis = document.querySelectorAll(selector);
    this.fall();
  }
  fall() {
    let position_arr = [];
    for (let i = 0; i < this.lis.length; i++) {
      if (i < 5) {
        position_arr.push({
          left: this.lis[i].offsetLeft,
          top: this.lis[i].offsetHeight
        });
      } else {
        let min_top = position_arr[0].top;
        let min_left = position_arr[0].left;
        let index = 0
        //获取位置信息数组的最小高度及其对应左侧距离
        for (let j = 0; j < position_arr.length; j++) {
          if (position_arr[j].top < min_top) {
            min_top = position_arr[j].top;
            min_left = position_arr[j].left;
            index = j;
          }
        }
        //设置第一排外元素的位置
        this.lis[i].style.left = min_left + 'px';
        this.lis[i].style.top = min_top + 25 + 'px';
        //更新位置信息数组
        position_arr[index].top += (this.lis[i].offsetHeight + 25);
      }
    }
    let maxTop = position_arr[0].top;
    for(let i=0; i<position_arr.length; i++) {
      if(position_arr[i].top > maxTop) {
        maxTop = position_arr[i].top;
      }
    }
    this.wrapper.style.height = maxTop + 'px';
  }
}

class Magnifier {
  constructor(imgbox, imgSelector, bigImgSelector, maskSelector, bigImgBoxSelector) {
    //初始化遮罩层与图片的比例
    this.scale = 0.6;
    this.imgBox = $(imgbox);
    //获取小图的尺寸
    this.img = $(imgSelector);
    this.img_size = {
      width: this.img.width(),
      height: this.img.height()
    },
    //获取大图尺寸
    this.bigImg = $(bigImgSelector);
    this.bigImg_size = {
      width: parseInt(getComputedStyle(this.bigImg[0]).width),
      height: parseInt(getComputedStyle(this.bigImg[0]).height)
    }
    //获取遮罩层
    this.mask = $(maskSelector);
    //获取大图显示区
    this.bigImgBox = $(bigImgBoxSelector);
    this.init();
    //初始化后获取遮罩层尺寸

    //由于mask不显示，所以要用computed
    this.mask_size = {
      width: parseInt(getComputedStyle(this.mask[0]).width),
      height: parseInt(getComputedStyle(this.mask[0]).height)
    }

    this.bindEvent();
  }
  init() {
    //根据初始缩放比计算遮罩层和大图显示区宽高
    this.mask.css({
      width: this.img_size.width * this.scale,
      height: this.img_size.width * this.scale
    });
    this.bigImgBox.css({
      width: this.bigImg_size.width * this.scale,
      height: this.bigImg_size.width * this.scale
    });
  }
  bindEvent() {
    this.imgBox.on('mousemove', (e) => {
      e = e || event;
      if(e.stopPropagation) {
        e.stopPropagation
      }
      let left = e.pageX - this.img.offset().left - this.mask_size.width / 2;
      let top = e.pageY - this.img.offset().top - this.mask_size.height / 2;
      left = left <= 0 ? 0 : left;
      left = left >= (this.img_size.width - this.mask_size.width) ? (this.img_size.width - this.mask_size.width) : left;
      top = top <= 0 ? 0 : top;
      top = top >= (this.img_size.height - this.mask_size.height) ? (this.img_size.height - this.mask_size.height) : top;
      this.mask.css({
        left: left,
        top: top
      });
      this.bigImg.css({
        left: -left / this.img_size.width * this.bigImg_size.width,
        top: -top / this.img_size.height * this.bigImg_size.height 
      });
    });
  }
}

function throttle(func, delay) {
  let flag = true;
  return function (...args) {
    if (!flag) return;
    flag = false;
    setTimeout(() => {
      func.apply(this, args);
      flag = true;
    }, delay);
  }
}

function cookie(name, value, options = {}) {
  //设置cookie时，必须要传name，value
  if(name && value) {
    if(options.expires) {
      let d = new Date();
      d.setHours(d.getHours() - 8);
      d.setHours(d.getHours() + options.expires);
      options.expires = d;
    }
    let cookie = [
      name + '=' + value,
      (options.domain ? 'domain=' + options.domain : ''),
      (options.path ? 'path=' + options.path : ''),
      (options.expires ? 'expires=' + options.expires : '')
    ].join(';');
    return document.cookie = cookie;
  }
  //删除cookie时，传入name,value为null
  if(name && value === null) {
    return cookie(name, 'delete', Object.assign({
      expires: -1
    }, options));
  }

  //查询cookie，只需要传入name
  if(name) {
    let cookies = document.cookie.split('; ');
    for(let i in cookies) {
      if(name === cookies[i].split('=')[0]) {
        return cookies[i].split('=')[1];
      }
    }
  }
}

function formData(data) {
  let str = '';
  for(let attr in data) {
    str += '&' + attr + '=' + data[attr];
  }
  str = str.slice(1);
  return str;
}

class Toast {
  constructor(options) {
    this.createToast(options);
  }
  createToast(options) {
    let toast = $('<div id="my-toast"></div>');
    toast.html(options.message);
    $('body').append(toast);
    toast.css({
      left: innerWidth,
      top: 20,
      color: options.color ? options.color : '#000'
    });
    toast.stop(true).animate({
      left: innerWidth - toast.outerWidth() - 40
    }, () => {
      setTimeout(() => {
        toast.stop(true).fadeOut(() => {
          toast.remove();
          options.callback && options.callback();
        });
      }, 2000);
    });
  }
}

